import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @program: nio-learning 学习笔记
 * @description: 阻塞式网络nio测试
 * @author: zhaoxianglong
 * @create: 2021-03-09 15:56
 **/
public class BlockingTest {

    /**
     * 服务端
     * @throws IOException io异常
     */
    @Test
    public void server() throws IOException {
        //创建服务通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        //绑定端口
        serverSocketChannel.bind(new InetSocketAddress(8080));

        //启动通道
        SocketChannel socketChannel = serverSocketChannel.accept();

        //创建缓冲区
        ByteBuffer allocate = ByteBuffer.allocate(1024);

        //循环 读取数据 数据已读完 ? 退出循环 : 继续
        while (socketChannel.read(allocate) != -1) {
            //切换读模式
            allocate.flip();

            //创建数组,用于读取缓冲区数据
            byte[] bytes = new byte[allocate.limit()];

            //将缓冲区数据放到数组中
            allocate.get(bytes , 0 , allocate.limit());

            //打印到控制台
            System.out.println(new String(bytes));

            //清空缓冲区
            allocate.clear();
        }

        //关闭通道
        socketChannel.close();
        serverSocketChannel.close();
    }

    /**
     * 客户端
     * @throws IOException io异常
     */
    @Test
    public void client() throws IOException {
        //创建通道
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8080));

        //创建缓冲区
        ByteBuffer allocate = ByteBuffer.allocate(1024);

        //存入数据
        allocate.put("你说啥?".getBytes());

        //切换读模式
        allocate.flip();

        //将缓冲区放入通道
        socketChannel.write(allocate);

        //清空缓冲区
        allocate.clear();

        //关闭通道
        socketChannel.close();
    }
}
